﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Configuration;
using System.IO;
using System.IO.IsolatedStorage;


using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Messages;

namespace FetchExpImpersonated
{
    public partial class Form1 : Form
    {
        private static IOrganizationService SERVICE = CommonLibrary.CrmSvcHelper.CreateService();
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            FetchExpression fetchExp = new FetchExpression(richTextBox1.Text.Trim());
            try
            {
                
                richTextBox2.Text = "";
                
                ExecuteFetchRequest request = new ExecuteFetchRequest();
                request.FetchXml = richTextBox1.Text.Trim();

               
                ExecuteFetchResponse result = (ExecuteFetchResponse)SERVICE.Execute(request);

                //Format XML string
                IsolatedStorageFile tmpFile = IsolatedStorageFile.GetUserStoreForDomain();
                IsolatedStorageFileStream tmpStream = tmpFile.CreateFile("tmpFormated");
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(result.FetchXmlResult);
                doc.Save(tmpStream);
                tmpStream.Close();
                tmpStream = tmpFile.OpenFile("tmpFormated", FileMode.Open);
                StreamReader reader = new StreamReader(tmpStream);
                richTextBox2.Text = reader.ReadToEnd();
                reader.Close();
                tmpStream.Close();

                


                
            }
            catch (Exception ex)
            {
                richTextBox2.Text = ex.ToString();
            }
        }


        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }
 
    }
}
